Page({
  data: {
    parrotList: [],
    filteredList: [],
    bannerList: [],
    showAdminBtn: false,
    shopAddress: {},
    allTags: [],     // 所有品种标签
    currentTags: [], // 当前显示标签
    tagPage: 0,      // 当前标签页
    tagsPerPage: 8,  // 每页显示标签数
    scrollLeft: 0,
    activeTag: null, // 当前选中标签
    showTagControls: false // 是否显示翻页控制
  },

  onLoad() {
    this.getBanners()
    const app = getApp()
    app.recordVisit('pages/index/index')
    app.checkAdmin().then(isAdmin => {
      this.setData({ showAdminBtn: isAdmin })
    })
    this.setData({
      shopAddress: app.globalData.shopAddress
    })
    this.getParrotList()
  },

  // 导航到店铺
  navigateToShop() {
    const {latitude, longitude, name, address} = this.data.shopAddress
    wx.openLocation({
      latitude,
      longitude,
      name,
      address,
      scale: 18
    })
  },

  // 获取鹦鹉列表
  async getParrotList() {
    try {
      const res = await wx.cloud.database()
        .collection('lalayingwu')
        .where({
          isPublished: true
        })
        .orderBy('sortOrder', 'asc')
        .get()
      
      const parrotList = res.data.map(item => ({
        ...item,
        gender: this.formatGender(item.gender)
      }))
      
      // 初始化标签数据
      this.initTags(parrotList)
      this.setData({ 
        parrotList,
        filteredList: parrotList 
      })
    } catch (err) {
      console.error('获取鹦鹉列表失败:', err)
      wx.showToast({ title: '加载失败', icon: 'none' })
    }
  },

  // 初始化标签数据
  initTags(parrotList) {
    const allTags = [...new Set(parrotList.map(item => item.breed))]
    this.setData({
      allTags,
      tagPage: 0,
      scrollLeft: 0
    }, () => {
      this.updateTagDisplay()
    })
  },

  // 更新标签显示
  updateTagDisplay() {
    const start = this.data.tagPage * this.data.tagsPerPage
    const currentTags = this.data.allTags.slice(start, start + this.data.tagsPerPage)
    this.setData({
      currentTags,
      showTagControls: this.data.allTags.length > this.data.tagsPerPage
    })
  },

  // 标签翻页
  scrollTags(e) {
    const direction = e.currentTarget.dataset.direction
    let page = this.data.tagPage
    const maxPage = Math.ceil(this.data.allTags.length / this.data.tagsPerPage) - 1
    
    if (direction === 'prev' && page > 0) {
      page--
    } else if (direction === 'next' && page < maxPage) {
      page++
    }
    
    this.setData({
      tagPage: page,
      scrollLeft: page * 500
    }, () => {
      this.updateTagDisplay()
    })
  },

  // 按标签筛选
  filterByTag(e) {
    const tag = e.currentTarget.dataset.tag
    if (this.data.activeTag === tag) {
      // 点击已选中的标签，取消筛选
      this.setData({
        activeTag: null,
        filteredList: this.data.parrotList
      })
    } else {
      // 筛选对应品种
      this.setData({
        activeTag: tag,
        filteredList: this.data.parrotList.filter(item => item.breed === tag)
      })
    }
  },

  // 查看详情
  viewDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/detail/index?id=${id}`
    })
  },

  // 跳转后台管理
  goAdmin() {
    wx.navigateTo({
      url: '/pages/admin/parrot/index'
    })
  },

  // 长按识别图片中的二维码
  scanQRCode() {
    const app = getApp()
    const qrCodeUrl = app.globalData.shopAddress.qrCodeUrl
    
    if (!qrCodeUrl || !qrCodeUrl.startsWith('cloud://')) {
      wx.showToast({ 
        title: '二维码配置错误', 
        icon: 'none',
        duration: 2000
      })
      console.error('二维码URL格式错误:', qrCodeUrl)
      return
    }

    wx.getImageInfo({
      src: qrCodeUrl,
      success: (res) => {
        wx.analyzeImage({
          path: res.path,
          type: 'QRCode',
          success: (result) => {
            if (result.result && result.result.length > 0) {
              wx.showToast({ 
                title: '识别成功: ' + result.result[0].text, 
                icon: 'none',
                duration: 2000
              })
            } else {
              wx.showToast({ 
                title: '未识别到二维码', 
                icon: 'none',
                duration: 2000
              })
            }
          },
          fail: (err) => {
            wx.showToast({ 
              title: `识别失败: ${err.errMsg}`,
              icon: 'none',
              duration: 2000
            })
          }
        })
      },
      fail: (err) => {
        wx.showToast({ 
          title: `获取图片失败: ${err.errMsg}`,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  // 格式化性别显示
  formatGender(gender) {
    const genderMap = {
      0: '公',
      1: '母',
      2: '未知'
    }
    return genderMap[gender] || gender
  },

  // 获取轮播图数据
  async getBanners() {
    try {
      const res = await wx.cloud.database()
        .collection('banners')
        .where({ isActive: true })
        .orderBy('sortOrder', 'asc')
        .get()
      this.setData({ bannerList: res.data })
    } catch (err) {
      console.error('获取轮播图失败:', err)
    }
  },

  // 轮播图点击跳转
  navigateBanner(e) {
    const link = e.currentTarget.dataset.link
    if (link) {
      wx.navigateTo({ url: link })
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    Promise.all([
      this.getParrotList(),
      this.getBanners()
    ]).finally(() => {
      wx.stopPullDownRefresh()
    })
  },

  // 转发给朋友（右上角菜单）
  onShareAppMessage() {
    const bannerImage = this.data.bannerList && this.data.bannerList.length > 0 
      ? this.data.bannerList[0].imageUrl 
      : '/images/icons/jingangyingwu.svg';
    
    return {
      title: '拉拉的鹦鹉小屋 - 专业的鹦鹉养殖',
      path: '/pages/index/index',
      imageUrl: bannerImage
    }
  },

  // 分享到朋友圈（右上角菜单）
  onShareTimeline() {
    const bannerImage = this.data.bannerList && this.data.bannerList.length > 0 
      ? this.data.bannerList[0].imageUrl 
      : '/images/icons/jingangyingwu.svg';
    
    return {
      title: '拉拉的鹦鹉小屋 - 专业的鹦鹉养殖',
      query: '',
      imageUrl: bannerImage
    }
  }
})
